package ch.penas.business.service;

import java.sql.Connection;
import java.sql.SQLException;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import org.apache.derby.tools.ij;
import org.eclipse.persistence.internal.jpa.EntityManagerImpl;

public abstract class AgendaAbstractMYSQL {

	private static String mDDLFileName = "/sql/createAgendaDB_MYSQL.sql";
	private static EntityManagerFactory mEntityManagerFactory;
	private static EntityTransaction mEntityTransaction;
	private static String mPersistenceUnit = "test";
	private static EntityManager mEntityManager;

	public static void initFixture() throws Exception {
		mEntityManagerFactory = Persistence.createEntityManagerFactory(
		mPersistenceUnit);
		mEntityManager = mEntityManagerFactory.createEntityManager();
		mEntityTransaction = mEntityManager.getTransaction();

		Connection connection = ((EntityManagerImpl) (mEntityManager
				.getDelegate())).getServerSession()
				.getAccessor().getConnection();

		ij.runScript(connection, AgendaAbstractMYSQL.class
				.getResourceAsStream(mDDLFileName),
				"UTF-8", System.out, "UTF-8");
	}

	public static void closeEntityManager() throws SQLException {
		mEntityManager.close();
		mEntityManagerFactory.close();
	}

	/**
	 * Getter de EntityManagerFactory.
	 *
	 * @return mEntityManagerFactory
	 */
	protected final EntityManagerFactory getEntityManagerFactory() {
		return mEntityManagerFactory;
	}

	/**
	 * Getter de EntityTransaction.
	 *
	 * @return mEntityTransaction
	 */
	protected final EntityTransaction getEntityTransaction() {
		return mEntityTransaction;
	}

	/**
	 * Getter de EntityManager.
	 *
	 * @return mEntityManager
	 */
	protected final EntityManager getEntityManager() {
		return mEntityManager;
	}
}